package encome.work.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import encome.work.dao.User;
import encome.work.service.UserService;
import encome.work.utils.HttpUtils;
import encome.work.utils.Result;
import encome.work.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 小程序接口
 * @Author 阿杰
 * @create 2021-12-11 22:24
 */
@Slf4j
@RestController
@RequestMapping("/mini")
@Api(tags = "小程序相关接口")
public class MiniController {

    @Value("${mini.appid}")
    private String appid;

    @Value("${mini.secret}")
    private String secret;

    @Resource
    private UserService userService;



    @ApiOperation(value = "微信小程序登录")
    @GetMapping("/login")
    public Result login(@RequestParam String code) {
        if (StringUtils.isEmpty(code)) {
            return Result.fail("登录失败, 请联系管理员！");
        }
        // 构建get请求
        String url = "https://api.weixin.qq.com/sns/jscode2session?" + "appid=" +
                appid +
                "&secret=" +
                secret +
                "&js_code=" +
                code +
                "&grant_type=authorization_code";
        String result = HttpUtils.getResponse(url);
        // 发送请求
        JSONObject jsonObject = JSON.parseObject(result);
        String openid = jsonObject.getString("openid");
        //微信头像、地址
        String sessionKey = jsonObject.getString("session_key");
        log.info("微信小程序唯一标识：{}", openid);
        return userService.miniLogin(openid, sessionKey);
    }

    @ApiOperation(value = "更新用户信息")
    @PostMapping("/update/info")
    public Result updateInfo(@RequestBody User user) {
        return userService.updateByOpenId(user);
    }




}
